from snipins import *
import argparse
import sys
import pickle
import os
import fnmatch

def get_files(file_list, pattern='*.java'):
    compile_files = list()
    for filename in file_list:
        if(os.path.isfile(filename) and fnmatch.fnmatchcase(filename, pattern)):
            compile_files.append(filename)
        elif(os.path.isdir(filename)):            
            if(filename != '.' and filename.startswith('.') and not filename.startswith('..')):
                continue
            else:
                for root, dirs, files in os.walk(filename):
                    compile_files.extend([os.path.join(root, file) for file in [file for file in fnmatch.filter(files, pattern)]])
    return compile_files

if __name__ == '__main__':

    # create the parser
    parser = argparse.ArgumentParser(
        description='Compile snips from a file or directory.  This results in one snips file to be used')

    # add the arguments
    parser.add_argument(
        'inputs', metavar='input', type=str, nargs='+',
        help='one of the files to be parsed to generate snips')
    parser.add_argument(
        '-o', '--output', type=argparse.FileType('w'), default=sys.stdout,
        help='the file where the snips should be written '
             '(default: write the snips to stdout)')

    # parse the command line
    args = parser.parse_args()

    snips = dict()
    files = get_files(args.inputs)
    for input in files:
        f = open(input, 'r')
        snips.update(get_snips(f))
        f.close()


    pickle.dump(snips, args.output)
    args.output.close()




